#include "stdafx.h"
#include "session_manager.h"
#include "ProtoMgr.h"

CPlayerSession::CPlayerSession( utility::network::session * pSession )
{
    m_pSession = pSession;
}


CPlayerSession::~CPlayerSession(void)
{
}

void CPlayerSession::on_established()
{

}

void CPlayerSession::on_disconnected()
{
	CPlayerSessionMgr::Instance()->ReleaseSession(this);
}

void CPlayerSession::on_error(int32 error_code, const char * error_message)
{
	on_disconnected();
}

void CPlayerSession::on_receive(const char *message, uint32 message_length)
{
    if (message_length < sizeof(uint32))
        return;
    uint32 nMsgID = ntohl(*((int *)message));

    try{
        CProtoMgr::Instance()->GetGSProto().Decode(nMsgID, message + sizeof(nMsgID), message_length - sizeof(nMsgID), this);
    }
    catch(...)
    {
        LOG(CRITICAL) << "receive error: MsgID=" << nMsgID << ", Length="<<message_length;
    }
}

bool CPlayerSession::Send( uint32 MsgID, ::google::protobuf::Message * pMessage )
{
    size_t nBufSize = pMessage->ByteSize() + sizeof(uint32);
    char * pBuf = (char *)alloca(nBufSize);

    uint32 * pHeader = (uint32*)pBuf;
    *pHeader = htonl(MsgID);

    void * pMsg = (void*)(pBuf + sizeof(uint32));

    bool bFlag = pMessage->SerializeToArray(pMsg, nBufSize - sizeof(uint32));
    if (!bFlag)
    {
        LOG(CRITICAL) << "failed to serialize PB Message to array. Type name is "<< pMessage->GetTypeName();
        return false;
    }
    if (m_pSession)
        m_pSession->send(pBuf, nBufSize);
    else
        return false;
    return true;
}

void CPlayerSession::Disconnect()
{
    if (m_pSession)
        m_pSession->disconnect();
}

void CPlayerSession::OnRecvLoginReq( GS_LOGIN_REQ_PKG * pPkg)
{

}
